/***
 *    Shop Register JavaScriptShop
 **/

$().ready(function () {

    // 注册窗口显示
    $.registerWindowShow = function () {

        $("#registerWindow").jqmShow();
    }

    // 协议窗口显示
    $.agreementWindowShow = function () {
        $("#agreementWindow").jqmShow();
    }

    // 注册窗口/b/customer/ajaxRegister
    var registerWindowHtml = '<div id="registerWindow" class="registerWindow">' +
        '<div class="windowTop"><div class="windowTitle">会员注册</div><a class="windowClose registerWindowClose" href="#" hidefocus="true"></a></div>' +
        '<div class="windowMiddle">' +
        '<form id="" action="" method="">' +
        '<table>' +
        '<tr style="display: none;">' +
        '<th>用户名: </th>' +
        '<td>' +
        '<input type="text" id="username" name="member.username" class="formText {required: true, username: true, minlength: 2, maxlength: 20, messages: {required: \'请输入用户名!\', username: \'不允许包含特殊字符!\', remote: \'用户名已存在,请重新输入!\'}}" title="用户名只允许包含中文、英文、数字和下划线!" /></td>' +
        '</tr>' + '<tr>' +
        '<th>手机号: </th>' +
        '<td>' +
        '<input type="text" id="phone" name="member.phone" class="formText {required: true, phone: true, minlength: 11, maxlength: 11, messages: {required: \'请输入手机号名!\', phone: \'必须为11位数字!\', remote: \'该手机号已注册!\'}}" title="请填写正确的手机号!" /></td>' +
        '</tr>' + '<tr>' +
        '<th>图形码: </th>' +
        '<td>' +
        '<input style="width: 100px" type="text" id="inputRandomCode" name="inputRandomCode" class="formText {required: true, authcode: true, minlength: 2, maxlength: 20, messages: {required: \'请输入图形码!\'}}" title="不区分大小写" /><img id="registerWindowCaptchaImage" style="height: 34px;width: 70px;margin-left: 10px;vertical-align: middle" src="/b/captcha"></td>' +
        '</tr>'
        + '<tr>' +
        '<th>验证码: </th>' +
        '<td>' +
        '<input style="width: 100px" type="text" id="phonecode" name="phonecode" class="formText {required: true, phonecode: true, messages: {required: \'请输入手机验证码!\'}}" title="短信验证码" /><input id="sendCode" style="" type="button" class=" "value="验证码"/></td>' +
        '</tr>' +
        '<tr>' +
        '<th>密&nbsp;&nbsp;&nbsp;码: </th>' +
        '<td>' +
        '<input type="password"  id="registerWindowPassword" name="member.password" class="formText {required: true, minlength: 4, maxlength: 20, messages: {required: \'请输入密码!\', minlength: \'密码长度不能小于4\', maxlength: \'密码长度不能大于20\'}}" /></td></tr>' +
        '<tr><th style="width: 0"></th><td ><div style="display: inline-flex;align-items: center;margin-top: 15px" class="i-checks">\n' +
        '<input type="checkbox" id="checkButton"/> <div style="margin-left: 10px">我已阅读并同意<a href="/template/default/html/protocol.html" style="color: #15abf3">《用户注册协议》</a></div>\n' +
        '</div></td>' +
        '</tr>' +
        '<th>&nbsp;</th><td><a type="" id="" class="registerWindowSubmit" value="" hidefocus="true" style="text-align: center">注册</a></td></tr>' +
        '</table>' +
        '</form>' +
        '</div><div class="windowBottom"></div>' +
        '</div>';

    // 协议窗口
    var agreementWindowHtml = '<div id="agreementWindow" class="agreementWindow"><div class="windowTop"><div class="windowTitle">注册协议</div><a class="windowClose agreementWindowClose" href="#" hidefocus="true"></a></div><div class="windowMiddle"><div id="agreementContent"></div><input type="button" id="agreementButton" class="agreementButton agreementWindowClose" value="" hidefocus="true" /></div><div class="windowBottom"></div></div>';

    $("body").prepend(registerWindowHtml).append(agreementWindowHtml);


    // 注册悬浮窗口
    $("#registerWindow").jqm({
        modal: true,// 是否开启模态窗口
        overlay: 10,// 屏蔽层透明度
        trigger: ".showRegisterWindow",// 激活元素
        closeClass: "registerWindowClose",// 关闭按钮
        onHide: function (hash) {
            $("#registerWindowForm").resetForm();
            hash.o.remove();
            hash.w.fadeOut();
        },
        onShow: function (hash) {
            hash.w.fadeIn();
            registerWindowCaptchaImageRefresh();
            $('.i-checks').iCheck({
                checkboxClass: 'icheckbox_flat-blue',
            });
        }
    }).jqDrag(".windowTop");

    // 协议悬浮窗口
    $("#agreementWindow").jqm({
        modal: true,// 是否开启模态窗口
        overlay: 30,// 屏蔽层透明度
        trigger: ".showAgreementWindow",// 激活元素
        closeClass: "agreementWindowClose",// 关闭按钮
        onShow: function (hash) {
            if ($.trim($("#agreementContent").html()) == "") {
                $.ajax({
                    beforeSend: function (data) {
                        $("#agreementContent").html('<span class="loadingIcon">&nbsp;</span> 加载中...');
                    },
                    url: JFinalshop.base + "/pc1/html/agreement",
                    success: function (data) {
                        $("#agreementContent").html(data);
                    }
                });
            }
            hash.w.fadeIn();
        }
    }).jqDrag(".windowTop");

    $("#agreementButton").click(function () {
        $("#isAgreeAgreement").attr("checked", true);
    });

    // 表单验证
    $("#registerWindowForm").validate({
        invalidHandler: function (form, validator) {
            $.each(validator.invalid, function (key, value) {
                $.tip(value);
                return false;
            });
        },
        errorPlacement: function (error, element) {
        },
        submitHandler: function (form) {
            $("#registerWindowSubmit").attr("disabled", true);
            $("#registerWindowForm").ajaxSubmit({
                dataType: "json",
                success: function (data) {
                    if (data.status == "success") {
                        $.tip(data.status, data.message);
                        $.flushHeaderInfo();
                        $("#registerWindow").jqmHide();
                    } else {
                        registerWindowCaptchaImageRefresh();
                        $("#registerWindowCaptcha").val("");
                        $.tip(data.status, data.message);
                    }
                    $("#registerWindowSubmit").attr("disabled", false);
                }
            });
        }
    });

    // 刷新验证码图片
    function registerWindowCaptchaImageRefresh() {
        $("#registerWindowCaptchaImage").attr("src", JFinalshop.base + "/b/captcha?timestamp=" + (new Date()).valueOf());
    }

    // 点击刷新验证码图片
    $("#registerWindowCaptchaImage").click(function () {
        registerWindowCaptchaImageRefresh();
    });
    $("#sendCode").click(function () {
        var $this = $(this);
        var sMobile = $("input[name='member.phone']").val();
        if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(sMobile))) {
            $.tip("请输入正确手机号!");
            return false;
        }
        var inputRandomCode = $("input[name='inputRandomCode']").val();
        if (!inputRandomCode) {
            $.tip("请输入图形码!");
            return false;
        }
        // var descCode = inputRandomCode.split("");
        var bases = new Base64();
        $.ajax({
            url: '/b/pc/customer/validateCaptcha',
            data: {
                "phone": bases.encode(sMobile),
                "inputRandomCode": bases.encode(inputRandomCode),
            },
            success: function (data) {
                if (data.state === 'fail') {
                    $.tip(data.info);
                    registerWindowCaptchaImageRefresh();
                    return false;
                } else {
                    var timmer = 60;
                    $this.attr('disabled', true);
                    var phoneCodeTimer = setInterval(function () {
                        if (timmer >= 1) {
                            timmer--;
                            $this.val(timmer + " s");
                        } else {
                            $this.val('验证码');
                            window.clearInterval(phoneCodeTimer);
                            $this.removeAttr('disabled');
                        }

                    }, 1000);

                }
            }
        })
    });

    $(".registerWindowSubmit").click(function () {
        // var username = $("input[name='member.username']").val();
        var password = $("input[name='member.password']").val();
        var rePassword = $("input[name='rePassword']").val();
        var phone = $("input[name='member.phone']").val();
        var phonecode = $("input[name='phonecode']").val();
        var regName = /^\w{4,12}$/;
        if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(phone))) {
            $.tip("请输入正确手机号!");
            return false;
        }
        var inputRandomCode = $("input[name='inputRandomCode']").val();
        if (!inputRandomCode) {
            $.tip("请输入图形码!");
            return false;
        }
        if (!phonecode) {
            $.tip("请输入验证码!");
            return false;
        }

        if (!password) {
            $.tip("请输入用密码!");
            return;
        }
        if (password.length < 4) {
            $.tip("密码不能小于4个字符!");
            return;
        }
        if(!$('#checkButton').is(':checked')){
            $.tip('请先同意注册协议');
            return false;
        }
        $.ajax({
            url: "/b/pc/customer/ajaxRegister",
            type: 'GET',
            data: {
                "member.phone": phone,
                "member.password": password,
                "phonecode": phonecode,
            },
            success: function (data) {
                if (data.state === "fail") {
                    $.tip(data.info);
                } else if (data.state === "ok") {
                    $.tip("恭喜您注册成功!");
                    setTimeout(function () {
                        location.reload();
                    }, 1500);

                }
            }
        });

    });


    function Base64() {
        // private property
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }

        // public method for decoding
        this.decode = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }

        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        }

        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }

});


